/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.jittojava.temp;

import com.inspur.edp.jittojava.context.entity.MavenDependency;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @Classname Utils
 * @Description TODO
 * @Date 2019/12/17 16:05
 * @Created by liu_bintr
 * @Version 1.0
 */
public class Utils {
    public static void installPackage(String projectPath, String currentJarPath,
        ArrayList<MavenDependency> dependencyArrayList) {
        // 组装命令
        String command = String.format("cmd /c cd %s", projectPath);
        Process process = null;
        if (currentJarPath != null && !currentJarPath.isEmpty()) {
            String addDependencyCommand = "mvn install:install-file -DgroupId=%1$s " +
                "-DartifactId=%2$s -Dversion=%3$s -Dpackaging=jar -Dfile=%4$s";
            for (MavenDependency dependency : dependencyArrayList) {
                String addCommand = String.format(addDependencyCommand, dependency.getGroupId(),
                    dependency.getArtifactId(), dependency.getVersion(), getPathString(String.format(currentJarPath + "\\%1$s",
                        dependency.getFile())));
                command = command.concat(" && " + addCommand);
            }
        }
        excecuteCommand(process, command, "添加bef相关jar包");
    }

    public static void excecuteCommand(Process process, String command, String funcMessage) {
        // 执行命令
        try {
            process = Runtime.getRuntime().exec(command);
            log(funcMessage + "开始...");
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                log(line);
            }
            process.waitFor();
            if (process.exitValue() == 1) {
                log(funcMessage + "失败");
            }
            log(funcMessage + "完成");
            process.destroy();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void log(String message) {
        Boolean showLog = true;
        if (showLog) {
            //todo
//            message
        }
    }

    public static String getAbsolutePathString(String path) {
        return new File(path).getAbsolutePath();
    }

    public ArrayList<MavenDependency> getExtendDependency() {
        String extendDependencyPath =
            this.getClass().getResource("/BefExtendMavenDependency.xml").toString();
        return readInternalDependency(extendDependencyPath);
    }

    private ArrayList<MavenDependency> readInternalDependency(String defaultDependencyPath) {
        ArrayList<MavenDependency> result = new ArrayList<>();
        Document doc = readDocument(defaultDependencyPath);
        Element rootElement = doc.getRootElement();
        List<Element> list = rootElement.elements();
        for (int i = 0; i < list.size(); i++) {
            Element ele = (Element) list.get(i);
            result.add(new MavenDependency(getTagValue(ele, MavenDependencyConst.groupId), getTagValue(ele, MavenDependencyConst.artifactId),
                getTagValue(ele, MavenDependencyConst.version), getTagValue(ele, MavenDependencyConst.file)));
        }
        return result;
    }

    private Document readDocument(String filePath) {
        SAXReader sr = new SAXReader();
        try {
            return sr.read(filePath);
        } catch (DocumentException e) {
            throw new RuntimeException("无效路径" + filePath);
        }
    }

    private String getTagValue(Element ele, String tagName) {
        Element tagElement = (Element) ele.element(tagName);
        if (tagElement == null) {
            return null;
        }
        return tagElement.getText();
    }

    private static String getPathString(String path) {
        return getAbsolutePathString(path);
    }

    public ArrayList<MavenDependency> getDefaultDependency() {
        String defaultDependencyPath =
            this.getClass().getResource("/BefProjectMavenDependency.xml").toString();
        return readInternalDependency(defaultDependencyPath);
    }

    public ArrayList<MavenDependency> getSgfExtendDependency() {
        String extendDependencyPath =
            this.getClass().getResource("/SgfExtendMavenDependency.xml").toString();
        return readInternalDependency(extendDependencyPath);
    }

}
